﻿using System.Collections.Generic;
using System.Data;
using System.Data.Objects;

namespace Citi.OTFPC.Resource.Domain.Utils
{
    public class Context
    {
        public static string ConnectionString;
        private static ResourceEntities instance;
        private static readonly object Padlock = new object();

        /// <summary>
        /// Instancia estática do Contexto de entidades
        /// </summary>
        public static ResourceEntities Instance
        {
            get
            {
                lock (Padlock)
                {
                    if (instance != null) return instance;

                    instance = ConnectionString != null 
                        ? new ResourceEntities(ConnectionString) 
                        : new ResourceEntities();

                    return instance;
                }
            }
        }

        public static void SaveChanges()
        {
            try
            {
                Instance.SaveChanges();
            }
            catch (UpdateException)
            {
                throw;
            }
            catch
            {
                ClearContext();
            }
        }

        public static void ClearContext()
        {
            IEnumerable<ObjectStateEntry> objectStateEntries =
                Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void Delete(object entity)
        {
            Instance.DeleteObject(entity);
            SaveChanges();
        }
    }
}
